package com.yc.pre.config.security;

import com.alibaba.fastjson.JSON;
import com.yc.pre.entity.PreUserJwtRes;
import com.yc.pre.entity.Result;
import com.yc.pre.entity.StatusCode;
import com.yc.pre.utils.JwtUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author baozhuangyu
 * @Date 2020/11/26  17:00
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    RedisTemplate redisTemplate;


    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {

        String token = request.getHeader("token");

        if (CorsUtils.isPreFlightRequest(request) || notNeedToken(request)) {
            doFilter(request, response, filterChain);
            return;
        }

        if (StringUtils.isNotBlank(token)) {
            log.info(token);
            String username = JwtUtil.parseJWT(token).getSubject();
            String value = (String) redisTemplate.opsForValue().get("PRE_SIGN_" + username + "_" + token);
            if (StringUtils.isEmpty(value)) {
                response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                response.getWriter().write(JSON.toJSONString(new Result(false, StatusCode.RE_LOGIN, "请登录")));
                return;
            }
            PreUserJwtRes jwtRes = JSON.parseObject(value, PreUserJwtRes.class);

            String roleName = jwtRes.getRoleName();
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            if (StringUtils.isNotBlank(roleName)){
                authorities.add(new SimpleGrantedAuthority(roleName));
            }

            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(jwtRes, null, authorities);
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext()
                    .setAuthentication(authentication);
            request.setAttribute("userId", jwtRes.getId());
            filterChain.doFilter(request, response);
        } else {

            filterChain.doFilter(request, response);
        }
    }

    public boolean notNeedToken(HttpServletRequest request) {
        List<String> ignoreList = new ArrayList<>(Arrays.asList("/favicon.ico", "/doc.html", "/swagger-resources/**"
                , "/css/**", "/js/**", "/docs/**", "/webjars/**", "/v2/api-docs", "/v2/api-docs-ext",
                "/api/index/**"));
        String method = request.getMethod();
        for (String ignore : ignoreList) {
            //一次一次遍历，如果url满足匹配的话，就是不需要token的了
            AntPathRequestMatcher matcher = new AntPathRequestMatcher(ignore, method);
            if (matcher.matches(request)) {
                return true;
            }
        }
        return false;
    }

}
